from tornado.web import RequestHandler
from core.request_handler import BaseHandler
from models.vsplider import Eacoo_video,Eacoo_play, UserInfo
from utils.log import Logger
from utils.pagination import Page

c_type={1:"电影",
    2:"电视剧",
    3:"综艺",
    4:"动漫"}
c_ch={1:"动作",
    2:"喜剧",
    3:"爱情",
    4:"科幻",
    5:"恐怖",
    6:"剧情",
    7:"战争",
    8:"记录",
    9:"音乐",
    10:"伦理",
    11:"福利"}
class IndexHandler(BaseHandler):
    def get(self):
        current_page = self.get_argument("p", 1)
        per_page_count = self.get_argument("pre", 50)
        try:
            current_page = int(current_page)
            per_page_count = int(per_page_count)
        except ValueError as e:
            Logger().log(e, True)
            self.redirect('/index')
        try:
            tit="";
            param="";
            where=(Eacoo_video.status==1)
            if self.get_argument("t", 0):
                tit +=c_type.get(int(self.get_argument("t", 0)),"")+"_"
                param +="t="+self.get_argument("t", 0)+"&"
                where = where & (Eacoo_video.type==self.get_argument("t", 0))
            if self.get_argument("c", ""):
                tit +=c_ch.get(int(self.get_argument("c", "")),"")+"_"
                param +="c="+self.get_argument("c", "")+"&"
                where = where & (Eacoo_video.channel.contains(","+self.get_argument("c", "")+","))
            data_count = Eacoo_video.select().where(where).count()
            # print(data_count.sql());exit();
            # if self.get_argument("t",0):
            #     data_count=Eacoo_video.select().where(Eacoo_video.type==self.get_argument("t",0)).count()
            # else:
            #     data_count = Eacoo_video.select().count()
            page_obj = Page(current_page=current_page, data_count=data_count, per_page_count=per_page_count)
            page_html = page_obj.page_str(base_url="index?"+param)
            at_list = []
            if current_page == 1:
                video_objs = Eacoo_video.select().where(where)[-page_obj.end:]
                # if self.get_argument("t", 0):
                #     video_objs = Eacoo_video.select().where(Eacoo_video.type==self.get_argument("t",0))[-page_obj.end:]
                # else:
                #     video_objs = Eacoo_video.select()[-page_obj.end:]
            else:
                video_objs = Eacoo_video.select().where(where)[-page_obj.end:-page_obj.start]
                # if self.get_argument("t", 0):
                #     video_objs = Eacoo_video.select().where(Eacoo_video.type==self.get_argument("t",0))[-page_obj.end:-page_obj.start]
                # else:
                #     video_objs = Eacoo_video.select()[-page_obj.end:-page_obj.start]

            for video_obj in video_objs:

                at_list.append({'id': video_obj.id,
                                'type': video_obj.type,
                                'typen': c_type.get(int(video_obj.type),"未知"),
                                'channel': video_obj.channel,
                                'name': video_obj.name,
                                'ads': video_obj.ads,
                                'update_time': video_obj.update_time
                                })
            at_list.reverse()
        except Exception as e:
            Logger().log(e, True)
            return self.render('index/500.html')
        if current_page == 1 and len(at_list) < per_page_count:
            page_html = ""
        # at_list=[]
        # page_html=""
        self.render('index/index.html', at_list=at_list, page_html=page_html,tit=tit)


class VodHandler(BaseHandler):
    def get(self, article_id=None):
        if article_id:
            try:
                video_obj = Eacoo_video.get(Eacoo_video.id == article_id)
                video_obj.typen=c_type.get(int(video_obj.type),"未知")
                video_obj.channeln="";
                arr_channel=video_obj.channel.split(',')
                for c in arr_channel:
                    if c:
                        video_obj.channeln +=c_ch.get(int(c),"")+","

                arr_playlist1=[]
                arr_playlist2=[]
                arr_playlist3=[]
                playlist=Eacoo_play.select().where((Eacoo_play.video==article_id) &
                                                   (Eacoo_play.type==int(1)))
                for pl in playlist:
                    arr_playlist1.append({
                        'id': pl.id,
                        'type': pl.type,
                        'title': pl.title,
                        'url': pl.url,
                        'update_time': pl.update_time
                    })
                playlist = Eacoo_play.select().where((Eacoo_play.video == article_id) &
                                                      (Eacoo_play.type == int(2)))
                for pl in playlist:
                    arr_playlist2.append({
                        'id': pl.id,
                        'type': pl.type,
                        'title': pl.title,
                        'url': pl.url,
                        'update_time': pl.update_time
                    })
                playlist = Eacoo_play.select().where((Eacoo_play.video == article_id) &
                                                     (Eacoo_play.type == int(3)))
                for pl in playlist:
                    arr_playlist3.append({
                        'id': pl.id,
                        'type': pl.type,
                        'title': pl.title,
                        'url': pl.url,
                        'update_time': pl.update_time
                    })
                # video_data = {'id': video_obj.id,
                #                 'name': video_obj.title,
                #                 'content': video_obj.content,
                #                 'read_count': video_obj.read_count,
                #                 'created_date': video_obj.created_date,
                #                 'update_date': video_obj.update_date,
                #                 'article_type': video_obj.article_type.article_type
                #                 }
                # Article.update(read_count=Article.read_count + 1).where(Article.id == article_id).execute()
                # n_video_obj = Article.select(Article.id).where(Article.id > article_id).order_by(Article.id.asc()).limit(1)
                # n_a_id = []
                # for i in n_video_obj:
                #     n_a_id.append(i.id)
                # if len(n_a_id) == 1:
                #     n_a_id = n_a_id[0]
                # else:
                #     n_a_id = article_id
                # video_data['n_a_id'] = n_a_id
                # p_video_obj = Article.select(Article.id).where(Article.id < article_id).order_by(Article.id.desc()).limit(1)
                # p_a_id = []
                # for i in p_video_obj:
                #     p_a_id.append(i.id)
                # if len(p_a_id) == 1:
                #     p_a_id = p_a_id[0]
                # else:
                #     p_a_id = article_id
                # video_data['p_a_id'] = p_a_id
            except Eacoo_video.DoesNotExist as e:
                Logger().log(e, True)
                return self.redirect('/404')
            except Exception as e:
                Logger().log(e, True)
                return self.render('index/500.html')
            return self.render('index/vod.html', video_data=video_obj,playlist1=arr_playlist1,playlist2=arr_playlist2,playlist3=arr_playlist3,tit=video_obj.name+"_")
        self.redirect('/404')


class SearchHandler(BaseHandler):
    def get(self):
        title = self.get_argument('wd', None)
        current_page = self.get_argument("p", 1)
        per_page_count = self.get_argument("pre", 50)
        try:
            current_page = int(current_page)
            per_page_count = int(per_page_count)
        except ValueError as e:
            Logger().log(e, True)
            self.redirect('/index')
        if title:
            try:
                data_count = Eacoo_video.select().where(Eacoo_video.name.contains(title)).count()
                if data_count <= 0:
                    return self.redirect('/404')
                page_obj = Page(current_page=current_page, data_count=data_count, per_page_count=per_page_count)
                page_html = page_obj.page_str(base_url="search?wd={_kw}&".format(_kw=title))
                search_list = []
                if current_page == 1:
                    search_objs = Eacoo_video.select().where(Eacoo_video.name.contains(title))[-page_obj.end:]
                else:
                    search_objs = Eacoo_video.select().where(Eacoo_video.name.contains(title))[-page_obj.end:-page_obj.start]
                for search_obj in search_objs:
                    search_list.append({'id': search_obj.id,
                                        'type': search_obj.type,
                                        'typen': c_type.get(int(search_obj.type),"未知"),
                                        'channel': search_obj.channel,
                                        'name': search_obj.name,
                                        'ads': search_obj.ads,
                                        'update_time': search_obj.update_time
                                        })
                search_list.reverse()
                if current_page == 1 and len(search_list) < per_page_count:
                    page_html = ""
                self.render('index/search.html', search_list=search_list, page_html=page_html,tit=title+"_")
            except Exception as e:
                Logger().log(e, True)
                return self.render('index/500.html')
        self.redirect('/index')


class TagsHandler(BaseHandler):
    def get(self, tag_id=None):
        current_page = self.get_argument("p", 1)
        per_page_count = self.get_argument("pre", 10)
        try:
            current_page = int(current_page)
            per_page_count = int(per_page_count)
        except ValueError as e:
            Logger().log(e, True)
            return self.redirect('/index')
        if tag_id:
            try:
                data_count = Article.select().where(Article.article_type_id == tag_id).count()
                if data_count <= 0:
                    return self.redirect('/404')
                page_obj = Page(current_page=current_page, data_count=data_count, per_page_count=per_page_count)
                page_html = page_obj.page_str(base_url="/tag/{_tid}?".format(_tid=tag_id, ))
                tag_list = []
                if current_page == 1:
                    tag_objs = Article.select().where(Article.article_type_id == tag_id)[-page_obj.end:]
                else:
                    tag_objs = Article.select().where(Article.article_type_id == tag_id)[-page_obj.end:-page_obj.start]
                for search_obj in tag_objs:
                    tag_list.append({'id': search_obj.id,
                                     'title': search_obj.title,
                                     'summary': search_obj.summary,
                                     'read_count': search_obj.read_count,
                                     'created_date': search_obj.created_date,
                                     'article_type': search_obj.article_type.article_type
                                     })
                tag_list.reverse()
                if current_page == 1 and len(tag_list) < per_page_count:
                    page_html = ""
                return self.render('index/tag.html', tag_list=tag_list, page_html=page_html,tit="")
            except Exception as e:
                Logger().log(e, True)
                return self.render('index/500.html')
        self.redirect('/index')


class AboutHandler(BaseHandler):
    def get(self):
        try:
            blog_obj = Blog.get(Blog.id == 1)
            user_obj = UserInfo.get(UserInfo.username == 'yang')
            about_data = {'username': user_obj.username,
                          'email': user_obj.email,
                          'about': blog_obj.about}
        except Exception as e:
            Logger().log(e, True)
            return self.render('index/500.html')
        self.render('index/about.html', about_data=about_data,tit="")


class NotfindHandler(BaseHandler):
    def get(self, *args, **kwargs):
        return self.render('index/404.html',tit="")


class ServerErrorHandler(RequestHandler):
    def get(self, *args, **kwargs):
        return self.render('index/500.html',tit="")